package com.example.util;

import io.lettuce.core.GeoArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String LOCK_KEY = "spike-lock";

    //获取锁
    public boolean Lock(String uid, long time, TimeUnit unit) {
        while (redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, uid, time, unit)) {
            try {
                System.out.println("正在排队");
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        extendTime(uid, time, unit);
        return true;

    }

    //释放锁
    public boolean unLock(String uid) {
        String lock = redisTemplate.opsForValue().get(LOCK_KEY);
        if (lock != null) {
            if (lock.equals(uid)) {
                redisTemplate.delete(LOCK_KEY);
                return true;
            }
        }
        return false;
    }

    //续期
    public void extendTime(String uid, long extime, TimeUnit unit) {
        Thread watchDogThread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(extime / 3 * 2);
                String lock = redisTemplate.opsForValue().get(LOCK_KEY);
                if (lock != null && lock.equals(uid)) {
                    redisTemplate.expire(LOCK_KEY, extime, unit);
                    System.out.println("用户" + uid + "以为你续期");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        watchDogThread.setDaemon(true);
        watchDogThread.start();
    }

    public boolean isHoldBycurrentThead() {
        String lock = redisTemplate.opsForValue().get(LOCK_KEY);
        String thead = Thread.currentThread().getName();
        return lock != null && lock.equals(thead);
    }


}
